package com.laolei.core.rest;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.laolei.core.rest.config.HostConfig;
import com.laolei.core.utils.StringUtils;

@Component
@EnableConfigurationProperties({ HostConfig.class })
@ComponentScan(basePackageClasses = { ScannerAndRegistrarBean.class, HttpRequestHandle.class, InvokeHandle.class })
public class RestClientAutoConfiguration implements BeanFactoryPostProcessor, EnvironmentAware {

	Environment environment;
	ScannerAndRegistrarBean scannerAndRegistrarBean = new ScannerAndRegistrarBean();

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		String basePackage = environment.getProperty("laolei.rest.base-package");
		if (StringUtils.isEmpty(basePackage))
			return;
		String[] basePackages = basePackage.split(",");
		Set<String> packages = new HashSet<>();
		for (String string : basePackages) {
			packages.add(string);
		}
		scannerAndRegistrarBean.registrarScannerBean(packages, beanFactory);
	}

}
